<?php

namespace app\service\Captcha;

use Fastknife\Service\BlockPuzzleCaptchaService;
use Fastknife\Service\ClickWordCaptchaService;
use think\facade\Validate;

class AjCaptchaService
{

    /**
     * 创建验证码
     * @param string $type 验证码类型：blockPuzzle-滑块 | clickWord-文字
     * @return array
     * @throws \Exception
     */
    public function create(string $type='blockPuzzle'): array
    {
        $service = $this->getCaptchaService($type);
        return $service->get();
    }

    /***
     * 第一次验证
     * @param $data
     * @return void
     * @throws \Exception
     */
    public function check($data)
    {
        $rules = [
            'token' => ['require'],
            'pointJson' => ['require'],
            'captchaType' => ['require']
        ];
        $msg = [
            'token' => '缺少参数token',
            'pointJson' => '缺少pointJson',
            'captchaType' => '缺少验证码类型'
        ];
        $validate = Validate::rule($rules, $msg)->failException(true);
        $validate->check($data);
        $service = $this->getCaptchaService($data['captchaType']);
        $service->check($data['token'], $data['pointJson']);
    }

    /**
     *  二次验证
     * @throws \Exception
     */
    public function verification(string $type, string $encryptCode)
    {

        $service = $this->getCaptchaService($type);
        $service->verificationByEncryptCode($encryptCode);
    }



    /** 获取验证码核心对象
     * @throws \Exception
     */
    protected function getCaptchaService($type): ClickWordCaptchaService|BlockPuzzleCaptchaService
    {
        $config = config('aj_captcha');
        switch ($type) {
            case 'clickWord':
                $service = new ClickWordCaptchaService($config);
                break;
            case 'blockPuzzle':
                $service = new BlockPuzzleCaptchaService($config);
                break;
            default:
                throw new \Exception("captchaType参数不正确！");
        }
        return $service;
    }

}
